/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import dto.Professor;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import org.jdesktop.observablecollections.ObservableCollections;//Incluir biblioteca "Vinculação de Beans".

/**
 *
 * @author davi
 */
public class ProfessorDAO {

    private EntityManagerFactory emf;
    private List<Professor> Professors = ObservableCollections.observableList(new ArrayList<Professor>());

    public ProfessorDAO(EntityManagerFactory emf) {
        this.emf = emf;
        leProfessores();
    }

    public void leProfessores(){
        EntityManager em = emf.createEntityManager();
        Query q = em.createQuery("select d from Professor d");
        Professors.clear();
        Professors.addAll(q.getResultList());
    }

    public boolean salvar(Professor Professor){
        EntityManager em = null;
        try {
            em = emf.createEntityManager();
            em.getTransaction().begin();
            em.merge(Professor);
            em.getTransaction().commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            if( em.isOpen() ){
                em.close();
            }
        }
        return false;
    }

    public boolean excluir(Professor Professor){
        EntityManager em = null;
        try {
            em = emf.createEntityManager();
            em.getTransaction().begin();
            // pega um objeto gerenciado pelo EntityManager para conseguir chamar
            // o método remove
            Professor disc = em.find(Professor.class, Professor.getId());
            em.remove(disc);
            em.getTransaction().commit();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            if( em.isOpen() ){
                em.close();
            }
        }
        return false;
    }

    public EntityManagerFactory getEmf() {
        return emf;
    }

    public void setEmf(EntityManagerFactory emf) {
        this.emf = emf;
    }

    public List<Professor> getProfessors() {
        return Professors;
    }

    public void setProfessors(List<Professor> Professors) {
        this.Professors = Professors;
    }





}
